import 'package:flutter/material.dart';
import '../../models/user_model.dart';
import '../../models/follow_category_model.dart';
import '../../models/post_model.dart';
import '../../models/post_type.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import 'management_center_page.dart';
import 'post_detail_page.dart';
import 'my_resources_page.dart';
import '../publish/publish_post_page.dart';
import '../hot/service_detail_page.dart';
import '../../utils/image_utils.dart';
import '../../widgets/rich_text_viewer.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final ApiService _apiService = ApiService();

  // 模拟未读系统消息数量
  int _unreadSystemMessages = 3;

  // 用户动态列表
  List<PostModel> _userPosts = [];
  bool _isLoadingPosts = false;
  String? _currentUserId;

  // 当前用户数据（从API加载）
  UserModel? _currentUser;
  bool _isLoadingUser = false;

  // 模拟关注分类数据
  final List<FollowCategory> _followCategories = [
    FollowCategory(
        id: '1',
        name: '家人',
        color: '#FF6B6B',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '2',
        name: '同事',
        color: '#4ECDC4',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '3',
        name: '高人',
        color: '#45B7D1',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '4',
        name: '朋友',
        color: '#96CEB4',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '5',
        name: '客户',
        color: '#FFEAA7',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '6',
        name: '合作伙伴',
        color: '#DDA0DD',
        isDefault: false,
        createdAt: DateTime.now()),
  ];

  /// 加载当前用户数据
  Future<void> _loadCurrentUser() async {
    setState(() => _isLoadingUser = true);

    try {
      // 获取当前用户ID
      final userId = await _apiService.getUserId();
      if (userId == null) {
        Logger.e('ProfilePage', '无法获取用户ID');
        return;
      }

      Logger.d('ProfilePage', '开始加载用户资料，用户ID: $userId');

      // 从API获取用户个人资料
      final profile = await _apiService.getUserProfile(userId);

      // 构建UserModel（暂时使用简化版本）
      setState(() {
        _currentUser = UserModel(
          id: userId,
          username: profile.username, // username是必填字段，不会为null
          email: profile.email ?? '',
          avatar: profile.avatarUrl ?? '',
          location: '',
          bio: profile.signature ?? '',
          skills: [],
          createdAt: profile.createTime ?? DateTime.now(),
        );
      });

      Logger.d('ProfilePage', '加载用户资料成功');
      Logger.d('ProfilePage', '用户昵称: ${profile.nickname}');
      Logger.d('ProfilePage', '头像URL: ${profile.avatarUrl}');
    } catch (e) {
      Logger.e('ProfilePage', '加载用户资料失败: $e');
      // 设置默认用户数据
      setState(() {
        _currentUser = UserModel(
          id: 'default',
          username: '用户',
          email: '',
          avatar: '',
          location: '',
          bio: '',
          skills: [],
          createdAt: DateTime.now(),
        );
      });
    } finally {
      setState(() => _isLoadingUser = false);
    }
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _loadCurrentUser(); // 加载用户数据
    _loadUserPosts();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 自定义AppBar
          SliverAppBar(
            expandedHeight: 300,
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              background: _buildUserHeader(),
            ),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.white),
              onPressed: () => Navigator.pop(context),
            ),
            actions: [
              // 系统消息图标
              Padding(
                padding: const EdgeInsets.only(right: 8.0),
                child: Stack(
                  children: [
                    IconButton(
                      icon: const Icon(Icons.notifications,
                          color: Colors.white, size: 28),
                      iconSize: 28,
                      onPressed: () => _showSystemMessages(),
                    ),
                    if (_unreadSystemMessages > 0)
                      Positioned(
                        right: 8,
                        top: 8,
                        child: Container(
                          padding: const EdgeInsets.all(2),
                          decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          constraints: const BoxConstraints(
                            minWidth: 16,
                            minHeight: 16,
                          ),
                          child: Text(
                            _unreadSystemMessages > 99
                                ? '99+'
                                : _unreadSystemMessages.toString(),
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 10,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
              // 管理中心按钮
              Padding(
                padding: const EdgeInsets.only(right: 16.0),
                child: TextButton.icon(
                  icon:
                      const Icon(Icons.settings, color: Colors.white, size: 20),
                  label: const Text(
                    '管理中心',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  onPressed: () => _navigateToManagementCenter(),
                ),
              ),
            ],
          ),
          // 用户信息卡片
          SliverToBoxAdapter(
            child: _buildUserInfoCard(),
          ),
          // 标签页
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverAppBarDelegate(
              TabBar(
                controller: _tabController,
                labelColor: Theme.of(context).primaryColor,
                unselectedLabelColor: Colors.grey,
                indicatorColor: Theme.of(context).primaryColor,
                tabs: const [
                  Tab(text: '动态'),
                  Tab(text: '我的资源'),
                ],
              ),
            ),
          ),
          // 标签页内容
          SliverFillRemaining(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildPostsTab(),
                const MyResourcesPage(), // 我的资源页面
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Theme.of(context).primaryColor,
            Theme.of(context).primaryColor.withOpacity(0.8),
          ],
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const SizedBox(height: 60),
          // 头像
          Container(
            width: 100,
            height: 100,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 4),
            ),
            child: _isLoadingUser
                ? const CircularProgressIndicator(color: Colors.white)
                : ImageUtils.safeAvatarImage(
                    _currentUser?.avatar,
                    size: 80,
                  ),
          ),
          const SizedBox(height: 16),
          // 用户名和认证标识
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                _currentUser?.username ?? '用户',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(width: 8),
              if (_currentUser?.certifications.isNotEmpty ?? false)
                const Icon(
                  Icons.verified,
                  color: Colors.amber,
                  size: 24,
                ),
            ],
          ),
          const SizedBox(height: 8),
          // 评分
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.star, color: Colors.amber, size: 20),
              const SizedBox(width: 4),
              Text(
                '${_currentUser?.rating ?? 0.0} (${_currentUser?.reviewCount ?? 0}评价)',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildUserInfoCard() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 个人简介
          if (_currentUser?.bio != null && _currentUser!.bio!.isNotEmpty) ...[
            const Text(
              '个人简介',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _currentUser!.bio!,
              style: const TextStyle(fontSize: 14, color: Colors.grey),
            ),
            const SizedBox(height: 16),
          ],
          // 统计信息
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                    '关注者', (_currentUser?.followersCount ?? 0).toString()),
              ),
              Container(
                width: 1,
                height: 40,
                color: Colors.grey[300],
              ),
              Expanded(
                child: _buildStatItem(
                    '关注中', (_currentUser?.followingCount ?? 0).toString()),
              ),
              Container(
                width: 1,
                height: 40,
                color: Colors.grey[300],
              ),
              Expanded(
                child: _buildStatItem(
                    '技能', (_currentUser?.skills.length ?? 0).toString()),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            color: Colors.grey[600],
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  Widget _buildPostsTab() {
    return RefreshIndicator(
      onRefresh: _loadUserPosts,
      child: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '我的动态',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              ElevatedButton.icon(
                onPressed: () => _showAddPostDialog(),
                icon: const Icon(Icons.add),
                label: const Text('发布动态'),
              ),
            ],
          ),
          const SizedBox(height: 16),
          // 动态列表
          if (_isLoadingPosts)
            const Center(child: CircularProgressIndicator())
          else if (_userPosts.isEmpty)
            const Center(
              child: Text(
                '暂无动态',
                style: TextStyle(color: Colors.grey),
              ),
            )
          else
            ..._userPosts.map((post) => Padding(
                  padding: const EdgeInsets.only(bottom: 12),
                  child: _buildPostCardFromModel(post),
                )),
        ],
      ),
    );
  }

  Widget _buildImageGrid(List<String> images) {
    // 过滤掉空的或无效的图片URL
    final validImages = images
        .where((url) =>
            url.isNotEmpty &&
            (url.startsWith('http://') || url.startsWith('https://')))
        .toList();

    if (validImages.isEmpty) {
      return const SizedBox.shrink(); // 如果没有有效图片，不显示任何内容
    }

    if (validImages.length == 1) {
      return CachedImageWidget(
        imageUrl: validImages[0],
        width: double.infinity,
        height: 200,
        fit: BoxFit.cover,
        borderRadius: BorderRadius.circular(8),
        imageType: '个人页图片',
      );
    } else {
      return GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: validImages.length > 9 ? 9 : validImages.length,
        itemBuilder: (context, index) {
          return CachedImageWidget(
            imageUrl: validImages[index],
            fit: BoxFit.cover,
            borderRadius: BorderRadius.circular(8),
            imageType: '个人页图片',
          );
        },
      );
    }
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Icon(
            icon,
            size: 20,
            color: Colors.grey[600],
          ),
          const SizedBox(width: 4),
          Text(
            label,
            style: TextStyle(
              color: Colors.grey[600],
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  void _navigateToManagementCenter() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const ManagementCenterPage(),
      ),
    );
  }

  void _showAddPostDialog() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const PublishPostPage(),
      ),
    );
  }

  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  void _showSystemMessages() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('系统消息'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildMessageItem('系统通知', '您的认证申请已通过审核', '2小时前'),
            const Divider(),
            _buildMessageItem('活动通知', '新用户注册活动开始啦', '1天前'),
            const Divider(),
            _buildMessageItem('更新通知', '应用已更新到最新版本', '3天前'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              setState(() {
                _unreadSystemMessages = 0;
              });
              Navigator.pop(context);
            },
            child: const Text('全部已读'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  Widget _buildMessageItem(String title, String content, String time) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
              Text(
                time,
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 12,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            content,
            style: const TextStyle(fontSize: 14),
          ),
        ],
      ),
    );
  }

  // 关注标签管理对话框
  void _showFollowCategoryManagementDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('关注标签管理'),
        content: SizedBox(
          width: double.maxFinite,
          height: 400,
          child: Column(
            children: [
              // 现有标签列表
              Expanded(
                child: ListView.builder(
                  itemCount: _followCategories.length,
                  itemBuilder: (context, index) {
                    final category = _followCategories[index];
                    return ListTile(
                      leading: Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(
                          color: Color(int.parse(
                              category.color.replaceAll('#', '0xFF'))),
                          shape: BoxShape.circle,
                        ),
                      ),
                      title: Text(category.name),
                      subtitle: Text(category.isDefault ? '默认标签' : '自定义标签'),
                      trailing: category.isDefault
                          ? null
                          : IconButton(
                              icon: const Icon(Icons.delete, color: Colors.red),
                              onPressed: () => _deleteCategory(category),
                            ),
                    );
                  },
                ),
              ),
              // 添加新标签按钮
              ElevatedButton.icon(
                onPressed: () => _showAddCategoryDialog(),
                icon: const Icon(Icons.add),
                label: const Text('添加自定义标签'),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  // 添加新标签对话框
  void _showAddCategoryDialog() {
    final TextEditingController nameController = TextEditingController();
    String selectedColor = '#FF6B6B';

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加自定义标签'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: nameController,
              decoration: const InputDecoration(
                labelText: '标签名称',
                hintText: '请输入标签名称',
              ),
            ),
            const SizedBox(height: 16),
            const Text('选择颜色：'),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              children: [
                '#FF6B6B',
                '#4ECDC4',
                '#45B7D1',
                '#96CEB4',
                '#FFEAA7',
                '#DDA0DD',
                '#FFB6C1',
                '#98FB98',
                '#87CEEB',
                '#DDA0DD',
                '#F0E68C',
                '#FFA07A'
              ]
                  .map((color) => GestureDetector(
                        onTap: () => selectedColor = color,
                        child: Container(
                          width: 30,
                          height: 30,
                          decoration: BoxDecoration(
                            color:
                                Color(int.parse(color.replaceAll('#', '0xFF'))),
                            shape: BoxShape.circle,
                            border: Border.all(
                              color: selectedColor == color
                                  ? Colors.black
                                  : Colors.transparent,
                              width: 2,
                            ),
                          ),
                        ),
                      ))
                  .toList(),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              if (nameController.text.isNotEmpty) {
                setState(() {
                  _followCategories.add(FollowCategory(
                    id: DateTime.now().millisecondsSinceEpoch.toString(),
                    name: nameController.text,
                    color: selectedColor,
                    isDefault: false,
                    createdAt: DateTime.now(),
                  ));
                });
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('标签添加成功')),
                );
              }
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  // 删除标签
  void _deleteCategory(FollowCategory category) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除标签'),
        content: Text('确定要删除标签"${category.name}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _followCategories.removeWhere((c) => c.id == category.id);
              });
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('标签删除成功')),
              );
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  // 处理动态操作
  void _handlePostAction(String action, String? postId) {
    if (postId == null) return;

    switch (action) {
      case 'edit':
        _editPost(postId);
        break;
      case 'make_private':
        _setPostVisibility(postId, 'private');
        break;
      case 'make_public':
        _setPostVisibility(postId, 'public');
        break;
      case 'delete':
        _deletePost(postId);
        break;
    }
  }

  // 编辑动态
  void _editPost(String postId) {
    // TODO: 跳转到编辑页面
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('编辑功能开发中...')),
    );
  }

  // 设置动态隐私
  void _setPostVisibility(String postId, String visibility) {
    final visibilityText = visibility == 'private' ? '私密' : '公开';

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('设为$visibilityText'),
        content: Text(
            '确定要将此动态设为$visibilityText吗？${visibility == 'private' ? '设为私密后只有您自己可以看到。' : '设为公开后所有人都可以看到。'}'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              try {
                await _apiService.setPostVisibility(postId, visibility);
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('动态已设为$visibilityText')),
                );
                // 重新加载动态列表
                _loadUserPosts();
              } catch (e) {
                Logger.e('SET_VISIBILITY', '设置隐私失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('设置失败: $e')),
                );
              }
            },
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 删除动态
  void _deletePost(String postId) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除动态'),
        content: const Text('确定要删除此动态吗？删除后将无法恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              try {
                await _apiService.deletePost(postId);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('动态已删除')),
                );
                // 重新加载动态列表
                _loadUserPosts();
              } catch (e) {
                Logger.e('DELETE_POST', '删除动态失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('删除失败: $e')),
                );
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  // 加载用户动态列表
  Future<void> _loadUserPosts() async {
    if (_isLoadingPosts) return;

    setState(() {
      _isLoadingPosts = true;
    });

    try {
      // 获取当前用户ID
      _currentUserId = await _apiService.getUserId();
      if (_currentUserId == null) {
        throw Exception('用户未登录');
      }

      final posts = await _apiService.getUserPosts(
        userId: _currentUserId!,
        page: 1,
        size: 20,
      );

      setState(() {
        _userPosts = posts;
        _isLoadingPosts = false;
      });
    } catch (e) {
      Logger.e('LOAD_USER_POSTS', '加载用户动态失败: $e');
      setState(() {
        _isLoadingPosts = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载动态失败: $e')),
        );
      }
    }
  }

  // 从PostModel构建动态卡片
  Widget _buildPostCardFromModel(PostModel post) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: InkWell(
        onTap: () => _navigateToPostDetail(post),
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 动态头部 - 包含时间和操作菜单
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    _getTimeAgo(post.createdAt),
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 12,
                    ),
                  ),
                  // 动态操作菜单
                  PopupMenuButton<String>(
                    icon: Icon(
                      Icons.more_vert,
                      color: Colors.grey[600],
                      size: 20,
                    ),
                    onSelected: (value) => _handlePostAction(value, post.id),
                    itemBuilder: (context) => [
                      const PopupMenuItem(
                        value: 'edit',
                        child: Row(
                          children: [
                            Icon(Icons.edit, size: 16),
                            SizedBox(width: 8),
                            Text('编辑'),
                          ],
                        ),
                      ),
                      PopupMenuItem(
                        value: post.visibility == 'private'
                            ? 'make_public'
                            : 'make_private',
                        child: Row(
                          children: [
                            Icon(
                              post.visibility == 'private'
                                  ? Icons.public
                                  : Icons.lock,
                              size: 16,
                            ),
                            const SizedBox(width: 8),
                            Text(
                                post.visibility == 'private' ? '设为公开' : '设为私密'),
                          ],
                        ),
                      ),
                      const PopupMenuItem(
                        value: 'delete',
                        child: Row(
                          children: [
                            Icon(Icons.delete, color: Colors.red, size: 16),
                            SizedBox(width: 8),
                            Text('删除', style: TextStyle(color: Colors.red)),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 8),
              // 封面图片（优先显示coverUrl）
              if (post.coverUrl != null && post.coverUrl!.isNotEmpty) ...[
                CachedImageWidget(
                  imageUrl: post.coverUrl,
                  width: double.infinity,
                  height: 200,
                  fit: BoxFit.cover,
                  borderRadius: BorderRadius.circular(8),
                  imageType: '动态封面',
                ),
                const SizedBox(height: 12),
              ],
              // 标题（如果有）
              if (post.title != null && post.title!.isNotEmpty) ...[
                Text(
                  post.title!,
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.w600),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 8),
              ],
              // 动态内容 - 支持富文本显示
              if (post.content.isNotEmpty)
                post.postType == PostType.article
                    ? RichTextViewer(
                        htmlContent: post.content,
                        defaultTextStyle: const TextStyle(fontSize: 14),
                        maxLines: 3, // 列表中限制行数
                        overflow: TextOverflow.ellipsis,
                      )
                    : Text(
                        post.content,
                        style: const TextStyle(fontSize: 14),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
              // 图片网格（如果没有封面但有图片列表）
              if ((post.coverUrl == null || post.coverUrl!.isEmpty) &&
                  post.images.isNotEmpty) ...[
                const SizedBox(height: 12),
                _buildImageGrid(post.images),
              ],
              const SizedBox(height: 12),
              // 互动按钮
              Row(
                children: [
                  _buildActionButton(
                    icon: Icons.favorite_border,
                    label: '${post.likesCount}',
                    onTap: () {},
                  ),
                  const SizedBox(width: 24),
                  _buildActionButton(
                    icon: Icons.comment,
                    label: '${post.commentsCount}',
                    onTap: () {},
                  ),
                  const SizedBox(width: 24),
                  _buildActionButton(
                    icon: Icons.share,
                    label: '${post.sharesCount}',
                    onTap: () {},
                  ),
                  const Spacer(),
                  // 隐私状态指示器
                  if (post.visibility == 'private')
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.orange[100],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.lock,
                            size: 12,
                            color: Colors.orange[700],
                          ),
                          const SizedBox(width: 4),
                          Text(
                            '私密',
                            style: TextStyle(
                              color: Colors.orange[700],
                              fontSize: 10,
                            ),
                          ),
                        ],
                      ),
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 跳转到动态详情页面
  void _navigateToPostDetail(PostModel post) {
    // 根据动态类型跳转到不同的详情页面
    if (post.postType == 'service') {
      // 商品类型跳转到商品详情页
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ServiceDetailPage(post: post),
        ),
      );
    } else {
      // 其他类型跳转到通用详情页
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PostDetailPage(post: post),
        ),
      );
    }
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar _tabBar;

  _SliverAppBarDelegate(this._tabBar);

  @override
  double get minExtent => _tabBar.preferredSize.height;

  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return false;
  }
}
